package com.geostar.constructionland.attachment.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;



/**
 * @ClassName: Base64Utils 
 * @Description: 数据加密解密工具类
 * 
 */
@Slf4j
public class Base64Utils {
	private static final String secret = "Resource"; 
	/**
	 * 此方法用于Base64加密
	 * @param msg
	 * @return
	 */
	public static String toEncode(String msg) {
		if (StringUtils.isNotBlank(msg)) {
			try {
				return new String(encode(encrypt(msg.getBytes("UTF-8"), secret.getBytes())));
			} catch (Exception e) {
				log.error("编码异常", e);
			}
		}
		return "";
	}

	/**
	 * 此方法用于Base64解密
	 * @param msg
	 * @return
	 */
	public static String toDecode(String msg) {
		if (StringUtils.isNotBlank(msg)) {
			try {
				return new String(decrypt(decode(msg), secret.getBytes()), "UTF-8");
			} catch (Exception e) {
				log.error("解码异常" + msg, e);
			}
		}
		return "";
	}

	private static String encode(byte[] bstr) {
		return new BASE64Encoder().encode(bstr);
	}

	private static byte[] encrypt(byte[] data, byte[] key) {
		try {
			SecureRandom sr = new SecureRandom();
			DESKeySpec dks = new DESKeySpec(key);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
			byte encryptedData[] = cipher.doFinal(data);
			return encryptedData;
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}

	private static byte[] decode(String str) throws Exception {
		byte[] bt = null;
		try {
			bt = new BASE64Decoder().decodeBuffer(str);
		} catch (Exception e) {
			throw e;
		}
		return bt;
	}

	private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
		try {
			SecureRandom sr = new SecureRandom();
			DESKeySpec dks = new DESKeySpec(key);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
			byte decryptedData[] = cipher.doFinal(data);
			return decryptedData;
		} catch (Exception e) {
			throw e;
		}
	}
}